﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace Reports
{
    class MailSender
    {

        public MailSender()
        {
        }

        //身份验证
        private NetworkCredential GetCredentials()
        {
            NetworkCredential myCredentials =
                new NetworkCredential(MailConfig.username, MailConfig.password);
            return myCredentials;
        }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="MsgTo">发送目标地址</param>
        /// <param name="MsgSubject">发送主题</param>
        /// <param name="MsgText">正文</param>
        public void SetMail(string MsgTo, string MsgSuBject, string MsgText)
        {
            SetMail(MsgTo, MsgSuBject, MsgText, null);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="MsgTo">发送目标地址</param>
        /// <param name="MsgSubject">发送主题</param>
        /// <param name="MsgText">正文</param>
        /// <param name="filepaths">是否需要发带附件的邮件</param>
        public void SetMail(string MsgTo, string MsgSubject, string MsgText, string[] filepaths)
        {
            try
            {


                SmtpClient SmptCl = new SmtpClient(MailConfig.host, MailConfig.port);
                SmptCl.Credentials = GetCredentials();


                MailMessage MailMsg = new MailMessage(MailConfig.from, MsgTo);
                MailMsg.BodyEncoding = System.Text.Encoding.UTF8;
                MailMsg.Subject = MsgSubject;
                MailMsg.Body = MsgText;
                MailMsg.IsBodyHtml = true;


                //可以添加多个附件
                if (filepaths != null)
                {
                    foreach (string filepath in filepaths)
                    {
                        MailMsg.Attachments.Add(new Attachment(string.Format(@"{0}", filepath)));//"d:b.doc"
                    }
                }

                SmptCl.Send(MailMsg);
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
            }
        }
    }
}
